/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.marcelo.agro.campanias.gui;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.Collection;
import java.util.List;
import javax.swing.*;
import org.knolle.interfaces.ConstantsInterface;
import org.marcelo.agro.core.api.InterfaceActividades;
import org.marcelo.agro.nodos.ActividadesChildFactory;
import org.marcelo.agro.nodos.ActividadesNode;
import org.marcelo.agro.entidades.Actividades;
import org.marcelo.agro.entidades.Campanas;
import org.marcelo.agro.entidades.LotesPorCampana;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.explorer.ExplorerManager;
import org.openide.explorer.ExplorerUtils;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.WindowManager;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//org.marcelo.agro.campanias.gui//Actvidades//EN",
autostore = false)
@TopComponent.Description(preferredID = "ActvidadesTopComponent",
//iconBase="SET/PATH/TO/ICON/HERE", 
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "editor", openAtStartup = false)
@ActionID(category = "Window", id = "org.marcelo.agro.campanias.gui.ActvidadesTopComponent")
@ActionReference(path = "Menu/File" /*
 * , position = 333
 */)
@TopComponent.OpenActionRegistration(displayName = "#CTL_ActvidadesAction",
preferredID = "ActvidadesTopComponent")
@Messages({
    "CTL_ActvidadesAction=Actvidades",
    "CTL_ActvidadesTopComponent=Actvidades Window",
    "HINT_ActvidadesTopComponent=This is a Actvidades window"
})
public final class ActvidadesTopComponent extends TopComponent implements ExplorerManager.Provider, LookupListener {

    public static final ExplorerManager em =new ExplorerManager();
    private Node root;
    
    private Lookup.Result result = null;
    private Lookup.Result result2 = null;
    
    private InterfaceActividades ia = Lookup.getDefault().lookup(InterfaceActividades.class); 
    final static String VENTANA_LOOKUP= "VistaCampanhasTopComponent";
    private LotesPorCampana lpc = null;
    private Campanas campania = null;
    
    public ActvidadesTopComponent() {
        initComponents();
        setName(Bundle.CTL_ActvidadesTopComponent());
        setToolTipText(Bundle.HINT_ActvidadesTopComponent());
        associateLookup(ExplorerUtils.createLookup(em, getActionMap()));
        initOutlineView();
    }
    
    /**
     * Metodo para inicializar el OutlineView
     */
    private void initOutlineView(){
        outlineView1.setPropertyColumns(
            /*ActividadesNode.ID, "ID",*/ 
            ActividadesNode.FECHA, "Fecha"
            , ActividadesNode.CAMPANIA, "Campaña"
            , ActividadesNode.LOTE, "Lote"
            , ActividadesNode.TIPO_ACTIVIDAD, "Tipo Actividad"
            , ActividadesNode.TIPO_PRODUCTO, "Tipo Producto"
            , ActividadesNode.PRODUCTO, "Producto"
            , ActividadesNode.CONTROL, "Control"
            , ActividadesNode.DOSIS, "Dosis"
            , ActividadesNode.PRECIO_UNITARIO, "Precio Unitario"
            , ActividadesNode.TOTAL, "Total"
            , ActividadesNode.COMENTARIO, "Comentario"
        );
        
        
        
        
        int condicion = JComponent.WHEN_IN_FOCUSED_WINDOW;
        InputMap inputMap = outlineView1. getInputMap(condicion);
        
        //Cr4eando las entradas de datos
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), ConstantsInterface.DELETE);
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0), ConstantsInterface.EDIT);
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0), ConstantsInterface.REFRESH);
        
        ActionMap actionMap = outlineView1.getActionMap();
        
        actionMap.put(ConstantsInterface.DELETE, new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent e) {
                NotifyDescriptor nd = new NotifyDescriptor.Confirmation("Borrar", "A pUnto de Borrar");
                DialogDisplayer.getDefault().notify(nd);
            }
        });
        
        getActionMap().put(ConstantsInterface.DELETE, new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent e) {
                NotifyDescriptor nd = new NotifyDescriptor.Confirmation("Borrar", "A pUnto de Borrar");
                DialogDisplayer.getDefault().notify(nd);
            }
        });
        
//        ((Outline) outlineView1.getOutline()).setRootVisible(false);
        
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        outlineView1 = new org.openide.explorer.view.OutlineView();
        jSeparator1 = new javax.swing.JSeparator();
        lblTotalActividades = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();

        jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);

        outlineView1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true));
        outlineView1.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jScrollPane1.setViewportView(outlineView1);

        org.openide.awt.Mnemonics.setLocalizedText(lblTotalActividades, org.openide.util.NbBundle.getMessage(ActvidadesTopComponent.class, "ActvidadesTopComponent.lblTotalActividades.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(ActvidadesTopComponent.class, "ActvidadesTopComponent.jLabel2.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle.getMessage(ActvidadesTopComponent.class, "ActvidadesTopComponent.jLabel3.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel4, org.openide.util.NbBundle.getMessage(ActvidadesTopComponent.class, "ActvidadesTopComponent.jLabel4.text")); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblTotalActividades, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 498, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 404, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblTotalActividades)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4))
                .addGap(15, 15, 15))
        );
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel lblTotalActividades;
    private org.openide.explorer.view.OutlineView outlineView1;
    // End of variables declaration//GEN-END:variables
    @Override
    public void componentOpened() {
        // TODO add custom code on component opening
        
        root = new AbstractNode(Children.create(new ActividadesChildFactory(ia.getAll()), true) );
        root.setDisplayName("Lista de Actividades");        
        
        em.setRootContext(root);
        
        result = WindowManager.getDefault().findTopComponent(VENTANA_LOOKUP).getLookup().lookupResult(LotesPorCampana.class);
        result2 = WindowManager.getDefault().findTopComponent(VENTANA_LOOKUP).getLookup().lookupResult(Campanas.class);
        result.addLookupListener(this);
        result2.addLookupListener(this);
        resultChanged(new LookupEvent(result));
        resultChanged(new LookupEvent(result2));
        
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    @Override
    public ExplorerManager getExplorerManager() {
        return em;
    }

    @Override
    public void resultChanged(LookupEvent le) {
        Lookup.Result r = (Lookup.Result) le.getSource();
        
        Collection<? extends LotesPorCampana> lotesPorCampanas=null;
        Collection<? extends Campanas> listCampanias=null;
       
        if (r.equals(result)) {
            //Iniciar Handle
        ProgressHandle handle = ProgressHandleFactory.createHandle("Cargando...");
        handle.start();
             lotesPorCampanas =  r.allInstances();
             if (lotesPorCampanas != null) {
               for (LotesPorCampana lotesPorCampana : lotesPorCampanas) {
                   lpc = lotesPorCampana;
                   setName("Actividades en: " +lotesPorCampana.getLotes().getNombre());
               }
               recargarNodos();
            }
         handle.finish();
        }
        else if (r.equals(result2)){
            ProgressHandle handle = ProgressHandleFactory.createHandle("Cargando...");
           handle.start();
           listCampanias =  r.allInstances();
           if (listCampanias != null){
               for (Campanas c : listCampanias) {
                   campania = c;
                   lpc = null;
                   setName("Actividades en: " +c.getNombre());
               }
               recargarNodos();
           }
           handle.finish();
        }        
    }
    
    /**
     * Metodo para volver a cargar los datos en el outline view
     */
    
    private void recargarNodos(){
        final List<Actividades> listaActividades ;
        
        if (lpc != null) {
            listaActividades = ia.getActividades(lpc);
        }
        else {
            listaActividades = ia.getActividades(campania);
        }
        root = new AbstractNode(Children.create(new ActividadesChildFactory(listaActividades), true) );
        em.setRootContext(root);
        //Finalizar Handle
        
        
    }

        
}
